package com.hippo.core.ui

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.hippo.core.config.AppConfig
import com.hippo.core.core.UserManger
import com.hippo.core.core.manager.ActivityStack
import com.hippo.core.core.manager.FileDownloader
import com.hippo.core.event.MessageEvent
import com.hippo.core.event.MessageEventBus
import com.hippo.core.respository.ApiRepository
import com.hippo.core.ui.components.SystemBarWrapper
import com.hippo.core.ui.components.UpdateDialog
import com.hippo.core.ui.navigation.AppNavHost
import com.hippo.core.ui.navigation.AppRoute
import com.hippo.core.ui.theme.HippoTheme
import com.hippo.core.vm.MainVM
import com.thingclips.smart.home.sdk.ThingHomeSdk
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {

    private val vm: MainVM by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityStack.pushActivity(this)
        enableEdgeToEdge()
        initCompose()
        if(UserManger.isLogin()){
            checkVersion()
        }
    }


    private fun initCompose() {

        setContent {

            val navController = rememberNavController()

            HippoTheme {
                SystemBarWrapper {
                    Box {
                        AppNavHost(
                            vm = vm,
                            navController,
                            Modifier
                                .fillMaxSize()
                                .systemBarsPadding()
                        )

                        handleMessageEvent(navController)
                    }
                }


            }

        }
    }

    @Composable
    fun handleMessageEvent(navController: NavController) {

        var showUpdateDialog by remember { mutableStateOf(false) }

        val eventState by vm.eventFlow.collectAsState(initial = null)

        val context = LocalContext.current

        LaunchedEffect(eventState) {
            when (eventState) {
                is MessageEvent.TokenExpired -> {
                    navController.navigate(AppRoute.LOGIN) {
                        popUpTo(AppRoute.LOGIN) {
                            inclusive = true
                        }
                    }
                }

                is MessageEvent.Toast -> {
                    Toast.makeText(
                        context,
                        (eventState as MessageEvent.Toast).msg,
                        Toast.LENGTH_SHORT
                    ).show()
                }

                is MessageEvent.NewVersion -> {
                    showUpdateDialog = true
                }

                else -> {

                }
            }
        }

        if (showUpdateDialog) {
            val newVersion = (eventState as MessageEvent.NewVersion).version
            UpdateDialog(
                version = newVersion,
                onDismissRequest = {
                    showUpdateDialog = false
                },
                onUpdate = {
                    if (newVersion.compulsory != 1) {
                        showUpdateDialog = false
                    }
                    newVersion.downloadPath?.let { FileDownloader.downloadFile(context, it) }
                }
            )
        }
    }

    private fun checkVersion() {
        lifecycleScope.launch {
            ApiRepository.getLastVersion(AppConfig.VERSION_NAME)
                .onSuccess {
                    if(it?.isUpdate == 1){
                        MessageEventBus.post(MessageEvent.NewVersion(it))
                    }
                }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        ActivityStack.popActivity(this)
        ThingHomeSdk.onDestroy();
    }

}
